package com.zhiyizhen.handheld.component.personal;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.yalantis.ucrop.UCrop;
import com.zhiyizhen.handheld.R;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.ImageLoader;
import com.zhiyizhen.handheld.common.ImageUtil;
import com.zhiyizhen.handheld.common.LogUtil;
import com.zhiyizhen.handheld.common.MD5Util;
import com.zhiyizhen.handheld.common.PictureManager;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.ToastUtil;
import com.zhiyizhen.handheld.common.view.BaseFragment;
import com.zhiyizhen.handheld.common.view.CommonDialog;
import com.zhiyizhen.handheld.common.view.CustomProgressDialog;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.personal.api.IPersonalService;
import com.zhiyizhen.handheld.component.personal.bean.AvatarReq;
import com.zhiyizhen.handheld.component.personal.bean.ModifyPasswordReq;
import com.zhiyizhen.handheld.component.workspace.api.IWorkspaceService;
import com.zhiyizhen.handheld.component.workspace.bean.EmpInfo;
import com.zhiyizhen.handheld.databinding.FragmentPersonalInfoBinding;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.observers.DisposableObserver;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class PersonalInfoFragment extends BaseFragment {
    private final static int RC_PICK = 0x1;
    private static final String FORMAT_IMG_NAME = "IMG-%s.jpg";
    private CustomProgressDialog mProgressDialog;
    private FragmentPersonalInfoBinding binding;
    private LoginBean loginBean;
    private File mCropFile;
    private File mCompressedFile;
    private EmpInfo empInfo;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentPersonalInfoBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getEmpInfo();
        }
    }

    private void initView() {
        loginBean = DataCache.getLoginBean();
        binding.avatarImg.setOnClickListener(v -> pick());
        binding.saveBtn.setOnClickListener(v -> updateInfo(empInfo.getAvatarUrl(), binding.notesEdit.getText().toString()));
        binding.modifyPasswordBtn.setOnClickListener(v -> showModifyPasswordDialog(this.getActivity()));
    }

    public void pick() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        try {
            startActivityForResult(intent, RC_PICK);
        } catch (ActivityNotFoundException e) {
            ToastUtil.showShort(R.string.open_album_failed);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case RC_PICK:
                    handlePickResult(data);
                    break;
                case UCrop.REQUEST_CROP:
                    handleCropResult(data);
                    break;
                default:
                    break;
            }
        }
    }

    private void handlePickResult(Intent data) {
        Uri uri = data.getData();
        if (uri == null) {
            ToastUtil.showShort(R.string.pick_photo_failed);
            return;
        }

        handleImage(uri);
    }

    private void handleImage(Uri imgUri) {
        cropImage(imgUri);
    }

    private void handleCropResult(Intent data) {
        if (mCropFile == null || !mCropFile.exists()) {
            ToastUtil.showShort(R.string.crop_photo_failed);
            return;
        }
        final Uri resultUri = UCrop.getOutput(data);
        compressImage(resultUri);
    }

    private void cropImage(Uri sourceUri) {
        mCropFile = createImageFile();
        Uri imageOut = Uri.fromFile(mCropFile);
        UCrop.Options uCropOptions = new UCrop.Options();
        uCropOptions.setHideBottomControls(true);
        uCropOptions.setMaxBitmapSize(1080);
        UCrop.of(sourceUri, imageOut)
                .withAspectRatio(9, 9)
                .withMaxResultSize(500, 500)
                .withOptions(uCropOptions)
                .start(getActivity(), this);
    }

    private File createImageFile() {
        File path = PictureManager.getInstance().getCompressFilePath(getActivity());
        String name = String.format(FORMAT_IMG_NAME, System.currentTimeMillis());
        return new File(path, name);
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new CustomProgressDialog(getActivity());
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setContentText(R.string.img_uploading);
        }
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    private void compressImage(final Uri imgUri) {
        showProgressDialog();
        Observable.create((ObservableOnSubscribe<File>) emitter -> {
                    mCompressedFile = createImageFile();
                    emitter.onNext(ImageUtil.compressImage(imgUri, mCompressedFile, false));
                    emitter.onComplete();
                }).compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new DisposableObserver<>() {
                    @Override
                    public void onNext(@NonNull File file) {
                        LogUtil.d("result ==== 22222");
                        uploadImage(file);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        hideProgressDialog();
                        LogUtil.d("result ==== 44444");
                        ToastUtil.showShort(R.string.compress_photo_failed);
                    }

                    @Override
                    public void onComplete() {
                        // do nothing
                    }
                });
    }

    private void getEmpInfo() {
        ServiceFactory.getService(IWorkspaceService.class)
                .getEmpInfo(loginBean.getToken(), loginBean.getClinicId())
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<EmpInfo> responseData) {
                        if (responseData != null && responseData.getData() != null) {
                            setEmpInfo(responseData.getData());
                        }
                    }

                });
    }

    private void setEmpInfo(EmpInfo empInfo) {
        this.empInfo = empInfo;
        if (!TextUtils.isEmpty(empInfo.getAvatarUrl())) {
            ImageLoader.Option option = ImageLoader.Option.create();
            option.setCircleCrop(true);
            ImageLoader.load(getActivity(), empInfo.getAvatarUrl(), binding.avatarImg, option);
        }

        binding.nameTv.setText(empInfo.getEmpName());
        binding.genderTv.setText(empInfo.getGenderString());
        binding.numberTv.setText(empInfo.getEmpNo());

        binding.roomTv.setText(empInfo.getDeptName());
        binding.titleTv.setText(empInfo.getTitle());
        binding.notesEdit.setText(empInfo.getNotes());

    }

    private CommonDialog dialog;

    public void showModifyPasswordDialog(Activity activity) {
        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_modify_password, (ViewGroup) activity.getWindow().getDecorView(), false);
        final EditText oldPasswordEdit = view.findViewById(R.id.oldPasswordEdit);
        final EditText newPasswordEdit = view.findViewById(R.id.newPasswordEdit);
        final EditText confirmPasswordEdit = view.findViewById(R.id.confirmPasswordEdit);

        CommonDialog.Builder builder = new CommonDialog.Builder(activity);
        builder.setView(view);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_button).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.cancel_btn1).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.okBtn).setOnClickListener(v -> {
            String oldPw = oldPasswordEdit.getText().toString();
            String newPw = newPasswordEdit.getText().toString();
            String confirmPw = confirmPasswordEdit.getText().toString();
            if (TextUtils.isEmpty(oldPw)) {
                ToastUtil.showShort("请输入原密码");
                return;
            }

            if (TextUtils.isEmpty(newPw)) {
                ToastUtil.showShort("请输入新密码");
                return;
            }

            if (!newPw.equals(confirmPw)) {
                ToastUtil.showShort("新密码和确认密码不一致");
                return;
            }
            updatePassword(oldPw, newPw, confirmPw);
        });
    }

    private void uploadImage(File imgFile) {
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), imgFile);
        MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("file", imgFile.getName(), imageBody);

        ServiceFactory.getService(IPersonalService.class)
                .uploadFile(loginBean.getToken(), imageBodyPart)
                .compose(RxJavaUtil.mainSchedulers())
                .as(RxJavaUtil.bindLifecycle(this))
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        final String result = responseData.getData();
                        updateInfo(result, empInfo.getNotes());
                    }

                    @Override
                    protected void onFinally() {
                        hideProgressDialog();
                    }
                });
    }

    private void updateInfo(String avatarUrl, String notes) {
        AvatarReq avatarReq = new AvatarReq(avatarUrl, notes);
        ServiceFactory.getService(IPersonalService.class)
                .updateUserInfo(loginBean.getToken(), loginBean.getClinicId(), avatarReq)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        if (responseData != null) {
                            ToastUtil.showShort(responseData.getMsg());
                        }
                    }

                    @Override
                    protected void onFinally() {
                        super.onFinally();
                        getEmpInfo();
                    }
                });
    }

    private void updatePassword(String oldPw, String newPw, String confirmPw) {
        ModifyPasswordReq avatarReq = new ModifyPasswordReq(MD5Util.md5MessageDigest(oldPw), MD5Util.md5MessageDigest(newPw), MD5Util.md5MessageDigest(confirmPw));
        ServiceFactory.getService(IPersonalService.class)
                .updatePassword(loginBean.getToken(), loginBean.getClinicId(), avatarReq)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        if (responseData != null) {
                            ToastUtil.showShort(responseData.getMsg());
                            dialog.dismiss();
                        }
                    }

                    @Override
                    protected void onFinally() {
                        super.onFinally();
                        getEmpInfo();
                    }
                });
    }
}
